<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
        .con {
            width: 600px;
            height: 600px;
            border: 1px solid;
            position: relative;
        }
        
        .con div {
            width: 180px;
            height: 180px;
            background-color: antiquewhite;
            position: absolute;
        }
    </style>
</head>

<body>
    <div class="con">
        <div style="left: 10px; top: 10px"></div>
        <div style="left: 33.33%; top: 10px"></div>
        <div style="left: 66.66%; top: 10px"></div>

        <div style="left: 10px; top: 33.33%"></div>
        <div style="left: 33.33%; top: 33.33%"></div>
        <div style="left: 66.66%; top: 33.33%"></div>

        <div style="left: 10px; top: 66.66%"></div>
        <div style="left: 33.33%; top: 66.66%"></div>
        <div style="left: 66.66%; top: 66.66%"></div>
    </div>
    <script>
        // 改变方块的颜色
        var arr = [
            "yellow",
            "pink",
            "red",
            "blue",
            "black",
            "green",
            "orange",
            "yellowgreen",
            "skyblue",
        ];
        // 获取所有div的元素
        var odiv = document.querySelectorAll(".con div");
        // 循环所有div
        odiv.forEach(function(i, k) {
            i.style.backgroundColor = arr[k];

            // 按下方块
            i.onmousedown = function(e) {
                // 获取横向数值
                var x = e.clientX - this.offsetLeft;
                var y = e.clientY - this.offsetTop;

                // 设置权重
                this.style.zIndex = 10;
                this.onmousemove = function(e) {
                    var xx = e.clientX;
                    var yy = e.clientY;
                    this.style.left = xx - x + "px";
                    this.style.top = yy - y + "px";
                };
                document.onmouseup = function() {
                    console.log(i);
                    i.onmousemove = "";
                    i.style.zIndex = 0;
                };
            };
        });
    </script>
</body>

</html>